package com.xiaoxin.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxin.admin.exception.BusinessException;
import com.xiaoxin.admin.interceptor.AdminHolder;
import com.xiaoxin.admin.mapper.AdminMapper;
import com.xiaoxin.commons.utils.Constants;
import com.xiaoxin.commons.utils.JwtUtils;
import com.xiaoxin.model.domain.Admin;
import com.xiaoxin.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /*
    * 用户登录
    * */
    public Map login(Map map) {
        // 获取请求参数
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        // 校验验证码是否一致
        String code = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (StringUtils.isEmpty(code) || verificationCode.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        // 查询admin对象 对象是否存在,密码是否正确
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Admin admin = adminMapper.selectOne(wrapper);
        password = SecureUtil.md5(password);
        if (admin == null || !password.equals(admin.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        // 生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id", admin.getId());
        tokenMap.put("username", admin.getUsername());
        String token = JwtUtils.getToken(tokenMap);
        // 构造返回
        Map retMap = new HashMap();
        retMap.put("token", token);
        return retMap;

    }

    /*
    * 获取用户信息
    * */
    public AdminVo profile() {
        Long id = AdminHolder.getId();
        Admin admin = adminMapper.selectById(id);
        return AdminVo.init(admin);
    }
}
